package cc.linker.steplink.crm.merchanth5.controller.acs;


import cc.linker.steplink.crm.commons.FeeConstants;
import cc.linker.steplink.crm.commons.constant.WcPayConstant;
import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.model.WcPayProperties;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.commons.utils.TransactionOrderUtil;
import cc.linker.steplink.crm.merchanth5.commons.RequestFilter;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.service.MaiBaoLaService;
import cc.linker.steplink.crm.merchanth5.service.MallBoomService;
import cc.linker.steplink.crm.merchanth5.service.MallService;
import cc.linker.steplink.crm.merchanth5.service.VipCustomerLogService;
import cc.linker.steplink.crm.merchanth5.service.acs.MerchantSalerService;
import cc.linker.steplink.crm.merchanth5.service.acs.MerchantSettingService;
import cc.linker.steplink.crm.merchanth5.service.acs.PurchaseProcessService;
import cc.linker.steplink.crm.merchanth5.service.common.SmsService;
import cc.linker.steplink.crm.merchanth5.util.ParamSignUtils;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * 联盟商家
 */

@Slf4j
@RestController
@RequestMapping("/acs/merchantsaler")
public class MerchantSalerController {
    @Autowired
    private MerchantSettingService merchantSettingService;

    @Autowired
    private MallService mallService;

//    @Autowired
//    private PurchaseProcessDao purchaseProcessDao;

    @Lazy
    @Autowired
    private PurchaseProcessService purchaseProcessService;

    @Autowired
    private MallBoomService mallBoomService;

    @Autowired
    private MerchantSalerService merchantSalerService;

    @Autowired
    private SystemProperties systemProperties;

    @Autowired
    private WcPayProperties wcPayProperties;

    @Autowired
    private HttpService httpService;

    @Autowired
    private PurchaseProcessDao purchaseProcessDao;

    @Autowired
    private MaiBaoLaService maiBaoLaService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RequestFilter requestFilter;
    @Autowired
    private VipCustomerLogService vipCustomerLogService;

//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;
//
//    // 调用返回结果
//    private static final String ACS_CREATE_ORDER_RESULT = "ACS:CREATE_ORDER_RESULT";


    @Value("${wcpay.payurl}")
    private String payurl;
    @Value("${wcpay.smsurl}")
    private String smsurl;
    @Value("${system.scrm.getwxlist}")
    private String doAddbAccountUrl;
    @Value("${system.scrm.sync.contentUrl}")
    private String synccontentUrl;


    /**
     * 获取用户角色
     *
     * @param request
     * @return
     */
    @GetMapping("/getuserjoinstatus")
    public Map getUserStatus(HttpServletRequest request) {
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();

        Map<String, Object> record = new HashMap();
        int isSaler = 0;//是否是联盟商家
        int isPromoter = 0;//是否是加盟代理
        int isAgent = 0;//是否是推广员
        String agentStatus = "";//推广员状态 0：正常，1：禁用
        Map<String, String> tmpParam = new HashMap<>();
        tmpParam.put("orgId", orgId);
        tmpParam.put("customerId", customerId);
        Integer salerCount = mallBoomService.getSalerCount(tmpParam);
        if (salerCount > 0) {
            isSaler = 1;
        }
        Integer promoterCount = mallBoomService.getPromoterCount(tmpParam);
        if (promoterCount > 0) {
            isPromoter = 1;
        }
        Integer agentCount = mallBoomService.getAgentCount(tmpParam);
        if (agentCount > 0) {
            isAgent = 1;
            agentStatus = mallBoomService.getAgentCountStatus(customerId);
        }
        record.put("zIsSaler", isSaler);
        record.put("zIsPromoter", isPromoter);
        record.put("zIsAgent", isAgent);
        record.put("agentStatus", agentStatus);


        int zgoodNum = 0;//是否发布过商品
        int zauthenticateState = 0;//是否认证
        Map<String, String> salerInfo = merchantSalerService.getSalerInfo(customerId, orgId);
        if (null != salerInfo) {
            if ("1".equals(salerInfo.get("goodNum"))) {
                zgoodNum = 1;
            }
            if ("1".equals(salerInfo.get("authenticateState"))) {
                zauthenticateState = 1;
            }
        }
        record.put("zgoodNum", zgoodNum);
        record.put("zauthenticateState", zauthenticateState);
        record.put("zifPhone", StringUtils.isEmpty(mallBoomService.getBindPhoneByCid(customerId)) ? 0 : 1);
        return record;
    }


    /**
     * 获取加盟代理状态
     *
     * @param request
     * @return
     */
    @GetMapping("/getpromoterstatus")
    public Map<String, Object> getPromoterStatus(HttpServletRequest request) {
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        Map<String, Object> customerInfo = mallBoomService.getCustomerInfoByCustomerId(customerId);
        return customerInfo;
    }

    /**
     * 判断该用户是否绑定过手机号
     *
     * @param request
     * @return
     */
    @GetMapping("/checkuserphone")
    public Boolean checkUserPhone(HttpServletRequest request) {
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        return StringUtils.isEmpty(mallBoomService.getBindPhoneByCid(customerId));
    }

    /**
     * 将手机号写入customer表
     *
     * @param params
     * @param request
     * @return
     * @throws GlobalException
     */
    @PostMapping("/saveuserphone")
    public Boolean saveUserPhone(@RequestBody Map<String, String> params, HttpServletRequest request) throws GlobalException, IOException, URISyntaxException {
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        if (StringUtils.isEmpty(params.get("phone"))) {
            throw GlobalException.build("参数错误");
        }
        params.put("orgId", orgId);
        params.put("customerId", customerId);
//        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
//        nvps.add(new BasicNameValuePair("businessType", "1020"));
//        nvps.add(new BasicNameValuePair("plantName", "STEPLINK"));
//        nvps.add(new BasicNameValuePair("mobilNumber", params.get("phone")));
//        nvps.add(new BasicNameValuePair("randomCode", params.get("code")));
//        String result = ParamSignUtils.callService(smsurl + "/sms/checkVerificationCode", nvps, 0, 0);

        String result = smsService.checkVerification(orgId, params.get("phone"), params.get("code"));

        Map ret = (Map) JSON.parse(result);
        if ((Integer) ret.get("rt") != 1) {
            throw GlobalException.build("验证码失效");
        }

        Map<String, String> salerParam = new HashMap<String, String>();
        salerParam.put("orgId", orgId);
        salerParam.put("customerId", customerId);
        Integer salerCount = mallBoomService.getSalerCount(salerParam);//判断该用户是不是小b
        if (salerCount > 0) {
            //生成小b用于登录cas的账号
            String casUserName = "mbl" + params.get("phone") + orgId;
            String casPassword = getRandom(6);
            Map<String, Object> pushData = new HashMap<>();
            pushData.put("orgcode", orgId);
            pushData.put("account", casUserName);
            pushData.put("username", wxUser.getNickname());
            pushData.put("pwd", DigestUtils.md5DigestAsHex(casPassword.getBytes()));
            String postres = httpService.doGet(doAddbAccountUrl + "?action=doAddbAccount", pushData);
            if (null == postres) {
                throw GlobalException.build("验证失败，请重试");
            }
            Map res = (Map) JSON.parse(postres);
            if ((Integer) res.get("RetCode") != 0) {
                switch ((Integer) res.get("RetCode")) {
                    case 3:
                        throw GlobalException.build("你已是麦爆啦店主，请勿重复开通");
                    case 5:
                        throw GlobalException.build("用户达到上限，请联系管理员");
                }
                throw GlobalException.build("系统繁忙，请稍后再试");
            }
            params.put("casUserId", res.get("UserID").toString());
            params.put("casUserName", casUserName);
            params.put("casPassword", casPassword);
            mallBoomService.savephone(params);
        }
        Map<String, Object> phoneData = new HashMap<>();
        phoneData.put("bindPhone", params.get("phone"));
        phoneData.put("customerId", customerId);
        mallBoomService.updateBindPhoneByCid(phoneData);
        return true;
    }

    public void getCasUser(String customerId) throws IOException, URISyntaxException {
        Map<String, Object> customerInfo = mallBoomService.getCustomerInfoByCustomerId(customerId);
        if (null == customerInfo) {
            throw GlobalException.build("用户信息不存在");
        }
        String orgId = customerInfo.get("orgId").toString();
        String phone = customerInfo.get("bindPhone").toString();
        String username = customerInfo.get("customerName").toString();
        if (StringUtils.isEmpty(username)) {
            username = "手机尾号" + phone.substring(phone.length() - 4) + "用户";
        }
        Map<String, String> salerParam = new HashMap<>();
        salerParam.put("orgId", orgId);
        salerParam.put("customerId", customerId);

        Integer salerCount = mallBoomService.getSalerCount(salerParam);//判断该用户是不是小b
        if (salerCount > 0) {
            //生成小b用于登录cas的账号
            String casUserName = "mbl" + phone + orgId;
            String casPassword = getRandom(6);
            Map<String, Object> pushData = new HashMap<>();
            pushData.put("orgcode", orgId);
            pushData.put("account", casUserName);
            pushData.put("username", username);
            pushData.put("pwd", DigestUtils.md5DigestAsHex(casPassword.getBytes()));
            LOGGER.info("pushData===" + JSON.serialize(pushData));
            LOGGER.info("url===" + doAddbAccountUrl);
            String postres = httpService.doGet(doAddbAccountUrl + "?action=doAddbAccount", pushData);
            if (null == postres) {
                throw GlobalException.build("验证失败，请重试");
            }
            LOGGER.info("postres===" + postres);
            Map res = (Map) JSON.parse(postres);
            if ((Integer) res.get("RetCode") != 0) {
                switch ((Integer) res.get("RetCode")) {
                    case 3:
                        throw GlobalException.build("你已是麦爆啦店主，请勿重复开通");
                    case 5:
                        throw GlobalException.build("用户达到上限，请联系管理员");
                    default:
                        break;
                }
                throw GlobalException.build("系统繁忙，请稍后再试");
            }
            Map<String, String> params = new HashMap<>();
            params.put("casUserId", res.get("UserID").toString());
            params.put("casUserName", casUserName);
            params.put("casPassword", casPassword);
            params.put("phone", phone);
            params.put("customerId", customerId);
            mallBoomService.savephone(params);
        }
    }


    private static String getRandom(int length) {
        StringBuilder val = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            val.append(random.nextInt(10));
        }
        return val.toString();
    }

    /**
     * 获取自定义名称
     *
     * @param request
     * @return
     */
    @GetMapping("/getorgtitles")
    public Map getOrgTitles(HttpServletRequest request) {
        WxUser wxUser = requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        Map<String, String> orgInfo = merchantSalerService.getOrgInfo(orgId);

        Map<String, Object> data = new HashMap<>();
        data.put("promoterName", "推广员");
        data.put("agentName", "加盟代理");
        data.put("salerName", "联盟商家");
        data.put("mallName", "联盟商城");
        if (null != orgInfo) {
            if (!StringUtils.isEmpty(orgInfo.get("promoterName"))) {
                data.put("promoterName", orgInfo.get("promoterName"));
            }
            if (!StringUtils.isEmpty(orgInfo.get("agentName"))) {
                data.put("agentName", orgInfo.get("agentName"));
            }
            if (!StringUtils.isEmpty(orgInfo.get("salerName"))) {
                data.put("salerName", orgInfo.get("salerName"));
            }
            if (!StringUtils.isEmpty(orgInfo.get("mallName"))) {
                data.put("mallName", orgInfo.get("mallName"));
            }
        }
        return data;
    }

    @PostMapping("/ordernotify")
    public void orderNotify(@RequestBody Map<String, Object> params) throws Exception {
        params.put("status", "20");
        params.put("txsn", params.get("transactionId"));
        params.put("orderSn", params.get("outTradeNo"));
        purchaseProcessService.payCallback(params);
    }

    public void savePCustomer(String customerId, String pcustomerId, String orgId) {
        Map<String, String> tmpParam = new HashMap<>();
        tmpParam.put("orgId", orgId);
        tmpParam.put("customerId", pcustomerId);
        Integer promoterCount = mallBoomService.getPromoterCount(tmpParam);
        //联盟商家和加盟代理绑定上下级
        if (promoterCount > 0) {
            Map<String, Object> ret = new HashMap<>();
            ret.put("pcustomerId", pcustomerId);
            ret.put("customerId", customerId);
            ret.put("parentShareWay", "scan");
            mallBoomService.saveCustomerParent(ret);
        }
    }

    /**
     * 创建联盟商家订单
     *
     * @param params
     * @param request
     * @return
     * @throws GlobalException
     */
    @PostMapping("/createorder")
    public Object createOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) throws GlobalException {
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        String openId = wxUser.getOpenid();

        String s = stringRedisTemplate.opsForValue().get("saler_order_" + customerId + "_" + wxUser.getPayMode().toString());
        if (!StringUtils.isEmpty(s)) {
            throw GlobalException.build("操作过于频繁，请稍后再试");
        }

        if (merchantSalerService.checkSaler(orgId)) {
            throw GlobalException.build("达到上限,无法创建");
        }
        ////B用户付钱，A用户受益

//        String openId = wxUser.getRealOpenid();
        String orderSn = TransactionOrderUtil.TYPE_SHOP + TransactionOrderUtil.getPrimaryKey();

        Integer sysAmount = mallBoomService.getJoinMoney(orgId);

        if (null == sysAmount) {
            Map<String, Object> stringObjectMap = setInit(orgId);
            sysAmount = (Integer) stringObjectMap.get("amount");
        }

        if (null == params.get("amount")) {
            throw GlobalException.build("参数错误");
        }
        if (sysAmount != Integer.parseInt(params.get("amount").toString())) {
            throw GlobalException.build("金额不一致，请重试");
        }
        String pid = "";
        if (!StringUtils.isEmpty(params.get("pid"))) {
            pid = params.get("pid").toString();
            if (pid.equals(customerId)) {
                throw GlobalException.build("请勿扫自己的二维码");
            }
        }

        Map<String, String> salerParam = new HashMap<>();
        salerParam.put("customerId", customerId);
        salerParam.put("orgId", orgId);
        salerParam.put("orderType", "saler");
        Integer payMode = wxUser.getPayMode() + 2;
        salerParam.put("payType", payMode.toString());
        HashMap<String, Object> salerOrderInfo = mallBoomService.getSalerOrder(salerParam);

        if (null != salerOrderInfo) {//有订单
            if ("0".equals(salerOrderInfo.get("payStatus").toString())) {//订单未支付,取订单信息去支付
                Map<String, String> tmpParam = new HashMap<>();
                tmpParam.put("amount", sysAmount.toString());
                tmpParam.put("orderSn", orderSn);
                tmpParam.put("pid", pid);
                tmpParam.put("customerId", customerId);
                tmpParam.put("orgId", orgId);
                tmpParam.put("payType", payMode.toString());
                tmpParam.put("orderType", "saler");
                tmpParam.put("orderSource", (String) params.get("orderSource"));
                mallBoomService.editSalerOrder(tmpParam);
            } else {//订单已支付，直接返回
                throw GlobalException.build("你已加入，请勿重复加入");
            }
        } else {//没有订单，创建订单去支付
            Map<String, String> tmpParam = new HashMap<>();
            tmpParam.put("orderSource", (String) params.get("orderSource"));
            tmpParam.put("orderSn", orderSn);
            tmpParam.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            tmpParam.put("amount", sysAmount.toString());
            tmpParam.put("pid", pid);
            tmpParam.put("orgId", orgId);
            tmpParam.put("customerId", customerId);
            tmpParam.put("payStatus", "0");
            tmpParam.put("payType", payMode.toString());
            tmpParam.put("orderType", "saler");
            mallBoomService.addSalerOrder(tmpParam);
        }

        if (wxUser.getPayMode() == 2 || wxUser.getPayMode() == 3) {//通联支付
            //app支付
            if ("2".equals(params.get("orderSource"))) {
                Map<String, Object> resParam = new HashMap<>();
                resParam.put("orderSn", orderSn);
                resParam.put("orderSource", params.get("orderSource"));
                return resParam;
            }

//            Map<String, Object> accountParam = new HashMap<>();
//            accountParam.put("customerId", customerId);
//            accountParam.put("orgId", orgId);
//            accountParam.put("openId", openId);
//            maiBaoLaService.checkCustomerAccount(accountParam);
            openId = wxUser.getPayOpenId();
            Map<String, Object> reqMap = new HashMap<>();
            String frontUrl = "";
            if(!StringUtils.isEmpty(params.get("frontUrl"))){
                frontUrl = params.get("frontUrl").toString();
            }
            reqMap.put("frontUrl", frontUrl);//支付后跳转前端地址
            reqMap.put("cashAmount", sysAmount);//现金支付金额
            String merchantFeeAccount = purchaseProcessService.getCustomerIdByFeeTypeAndOrdId(FeeConstants.MERCHANT_FEE, orgId, wxUser.getPayMode());//分账卡号
            String cashSplitItems = this.getSplitItem(sysAmount, orderSn, orgId, "开通联盟商家", merchantFeeAccount, wxUser.getPayMode());
            reqMap.put("cashSplitItems", cashSplitItems);//现金分账明细，JSON字符串
            reqMap.put("customerId", customerId);//支付用户ID
            reqMap.put("goodsName", "开通联盟商家");//商品描述
            reqMap.put("openID", openId);//支付用户OPENID
            reqMap.put("orderSn", orderSn);//平台订单ID
            reqMap.put("payeeAccountNumber", merchantFeeAccount);//收款用户帐号(收款用户为机构会员时必填，机构结算标识)
            reqMap.put("payeeUserID", purchaseProcessDao.getAccountUidByOrgId(orgId));//收款用户ID

            // 行业代码
            String industryCode = purchaseProcessDao.getOrgMerchantInfoByOrgId(orgId);
            reqMap.put("industryCode", industryCode);
            // 行业名称
            String industryName = purchaseProcessDao.getIndustryNameByCode(industryCode);
            reqMap.put("industryName", industryName);
            // 应用appId
            String appId = "";
            if (wxUser.getPayMode() == 3) {
                appId = purchaseProcessDao.getAppIdByOrgId("linker");
            }
            if (wxUser.getPayMode() == 2) {
                appId = purchaseProcessDao.getAppIdByOrgId(orgId);
            }
            reqMap.put("appId", appId);
            String alias = "";
            if (wxUser.getPayMode() == 3) {
                alias = maiBaoLaService.getAliasByLinker();
            }
            if (wxUser.getPayMode() == 2) {
                alias = maiBaoLaService.getAlias(orgId);
            }
            reqMap.put("clintType", alias);
            // 支付方式：WX-公众号支付；XCX-微信小程序支付
            reqMap.put("payType", "WX");
            // 访问终端类型:1手机；2PC
            reqMap.put("source", 1);
            // 交易验证方式：0-无验证；1-短信验证码；2-支付密码
            reqMap.put("validateType", 0);

            String result = "";
            String url = wcPayProperties.getAcsurl() + WcPayConstant.TRADE_PAY_ORDER;
            try {
                // 积分抵扣为0元
                result = httpService.doPost(url, com.alibaba.fastjson.JSON.toJSONString(reqMap), WcPayConstant.JSON);
                result = purchaseProcessService.callResultProcess(result);
            } catch (Exception e) {
                LOGGER.error("支付网关调用异常", e);
                throw GlobalException.build("支付网关调用异常");
            }
            Map res = (Map) JSON.parse(result);
            // noinspection unchecked
            res.put("orderSn", orderSn);
            res.put("orderSource", params.get("orderSource"));
            stringRedisTemplate.opsForValue().set("saler_order_" + customerId + "_" + wxUser.getPayMode().toString(), "1", 200, TimeUnit.SECONDS);
            return res;
        } else {//微信支付
            SortedMap<String, Object> finalpackage = new TreeMap<>();
            Map<String, String> orderParam = new HashMap<>();
            Long currentTime = new Date().getTime();
            String notifyUrl = systemProperties.getScrmUrl() + "/acs/merchantsaler/ordernotify";
            orderParam.put("body", "开通联盟商家");
            orderParam.put("notifyUrl", notifyUrl);
            orderParam.put("openid", openId);
            orderParam.put("outTradeNo", orderSn);
            orderParam.put("timestamp", currentTime.toString());
            orderParam.put("totalFee", sysAmount.toString());
            orderParam.put("tradeType", "JSAPI");
            orderParam.put("wcpayType", "STEPLINK_" + orgId);

            Map<String, String> appSign = ParamSignUtils.sign(orderParam);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("appSign", appSign.get("appSign")));
            nvps.add(new BasicNameValuePair("notifyUrl", orderParam.get("notifyUrl")));
            nvps.add(new BasicNameValuePair("body", orderParam.get("body")));
            nvps.add(new BasicNameValuePair("outTradeNo", orderParam.get("outTradeNo")));
            nvps.add(new BasicNameValuePair("openid", orderParam.get("openid")));
            nvps.add(new BasicNameValuePair("timestamp", orderParam.get("timestamp")));
            nvps.add(new BasicNameValuePair("totalFee", orderParam.get("totalFee")));
            nvps.add(new BasicNameValuePair("tradeType", orderParam.get("tradeType")));
            nvps.add(new BasicNameValuePair("wcpayType", orderParam.get("wcpayType")));
            String result = ParamSignUtils.callService(payurl + "/pay/wcpay", nvps, 0, 0);
            Object parse = JSON.parse(result);
            Map ret = (Map) parse;
            if ((Integer) ret.get("rt") != 1) {
                throw GlobalException.build("微信签名失败");
            } else {
                Map retInfo = (Map) ret.get("object");
                finalpackage.put("appId", retInfo.get("appId"));
                finalpackage.put("timeStamp", retInfo.get("timeStamp"));
                finalpackage.put("nonceStr", retInfo.get("nonceStr"));
                finalpackage.put("package", "prepay_id=" + retInfo.get("prepayId"));
                finalpackage.put("signType", retInfo.get("signType"));
                finalpackage.put("paySign", retInfo.get("paySign"));
                finalpackage.put("orderSn", orderSn);
                finalpackage.put("orderSource", params.get("orderSource"));
            }
            stringRedisTemplate.opsForValue().set("saler_order_" + customerId + "_" + wxUser.getPayMode().toString(), "1", 200, TimeUnit.SECONDS);
            return finalpackage;
        }
    }


    //app支付，请求签名
    @PostMapping("/getsalerapppaysign")
    public Object getAppPaySign(@RequestBody Map<String, Object> params) {
        String orderSn = (String) params.get("orderSn");
        String openId = (String) params.get("openId");
        if (StringUtils.isEmpty(orderSn) || StringUtils.isEmpty(openId)) {
            throw GlobalException.build("参数错误");
        }
        String typeString = stringRedisTemplate.opsForValue().get("orderType_" + orderSn);
        Integer type;
        if (StringUtils.isEmpty(typeString)) {
            type = purchaseProcessDao.checkOrderTypeByPySn(params);
        } else {
            LOGGER.info("订单回调类型缓存：" + typeString);
            type = Integer.valueOf(typeString);
        }
        if (type == 5) {
            //会员
            return vipCustomerLogService.getVipAppPaySign(orderSn, openId);
        }

        HashMap<String, Object> salerOrderInfo = mallBoomService.getSalerOrderBySn(orderSn);
        if (null == salerOrderInfo) {
            throw GlobalException.build("系统繁忙，请稍后再试");
        }
        String tit = "";
        String feeAccount = "";
        String redisKey = "";
        if ("saler".equals(salerOrderInfo.get("orderType"))) {
            tit = "开通联盟商家";
            feeAccount = FeeConstants.MERCHANT_FEE;
            redisKey = "saler_order_";
        } else {
            tit = "开通加盟代理";
            feeAccount = FeeConstants.AGENT_FEE;
            redisKey = "promoter_order_";
        }

        String customerId = (String) salerOrderInfo.get("customerId");
        String orgId = (String) salerOrderInfo.get("orgId");
        Integer sysAmount = Integer.parseInt(salerOrderInfo.get("amount").toString());

        Integer payMode = mallService.getPayModeByOrgId(orgId);
        Map<String, Object> reqMap = new HashMap<>();
        reqMap.put("cashAmount", sysAmount);//现金支付金额
        String merchantFeeAccount = purchaseProcessService.getCustomerIdByFeeTypeAndOrdId(feeAccount, orgId, payMode);//分账卡号
        String cashSplitItems = this.getSplitItem(sysAmount, orderSn, orgId, tit, merchantFeeAccount, payMode);
        reqMap.put("cashSplitItems", cashSplitItems);//现金分账明细，JSON字符串
        reqMap.put("customerId", customerId);//支付用户ID
        reqMap.put("goodsName", tit);//商品描述
        reqMap.put("openID", openId);//支付用户OPENID
        reqMap.put("orderSn", orderSn);//平台订单ID
        reqMap.put("payeeAccountNumber", merchantFeeAccount);//收款用户帐号(收款用户为机构会员时必填，机构结算标识)
        reqMap.put("payeeUserID", purchaseProcessDao.getAccountUidByOrgId(orgId));//收款用户ID

        // 行业代码
        String industryCode = purchaseProcessDao.getOrgMerchantInfoByOrgId(orgId);
        reqMap.put("industryCode", industryCode);
        // 行业名称
        String industryName = purchaseProcessDao.getIndustryNameByCode(industryCode);
        reqMap.put("industryName", industryName);
        //应用appId
        String appId = purchaseProcessDao.getXcxAppIdByOrgId(orgId);
        reqMap.put("appId", appId);
        String alias = maiBaoLaService.getAlias(orgId);
        reqMap.put("clintType", alias);
        // 支付方式：WX-公众号支付；XCX-微信小程序支付
        reqMap.put("payType", "XCX");
        // 访问终端类型:1手机；2PC
        reqMap.put("source", 1);
        // 交易验证方式：0-无验证；1-短信验证码；2-支付密码
        reqMap.put("validateType", 0);

        String result = "";
        String url = wcPayProperties.getAcsurl() + WcPayConstant.TRADE_PAY_ORDER;
        try {
            // 积分抵扣为0元
            result = httpService.doPost(url, com.alibaba.fastjson.JSON.toJSONString(reqMap), WcPayConstant.JSON);
            result = purchaseProcessService.callResultProcess(result);
        } catch (Exception e) {
            LOGGER.error("支付网关调用异常", e);
            throw GlobalException.build("支付网关调用异常");
        }
        Map res = (Map) JSON.parse(result);
        // noinspection unchecked
        res.put("orderSn", orderSn);
        res.put("orderSource", "2");
        stringRedisTemplate.opsForValue().set(redisKey + customerId + "_2", "1", 200, TimeUnit.SECONDS);
        return res;
    }

    /**
     * 直接加入联盟商家（金额0）
     *
     * @param params
     * @param request
     * @return
     */
    @PostMapping("/joindirect")
    public Object joinDirect(@RequestBody Map<String, String> params, HttpServletRequest request) throws GlobalException {
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();

//        if (2 == wxUser.getPayMode()) {
//            Map<String, Object> accountParam = new HashMap<>();
//            accountParam.put("customerId", customerId);
//            accountParam.put("orgId", orgId);
//            accountParam.put("openId", openId);
//            maiBaoLaService.checkCustomerAccount(accountParam);
//        }

        if (merchantSalerService.checkSaler(orgId)) {
            throw GlobalException.build("达到上限,无法创建");
        }
        Integer amount = mallBoomService.getJoinMoney(orgId);
        if (null == amount) {
            Map<String, Object> stringObjectMap = setInit(orgId);
            amount = (Integer) stringObjectMap.get("amount");
        }
        if (amount > 0) {
            throw GlobalException.build("非法操作");
        }

        Map<String, String> tmpParam = new HashMap<>();
        tmpParam.put("orgId", orgId);
        tmpParam.put("customerId", customerId);
        Integer salerCount = mallBoomService.getSalerCount(tmpParam);
        if (salerCount > 0) {
            throw GlobalException.build("你已加入，请勿重复加入");
        }

        String pid = "";
        if (!StringUtils.isEmpty(params.get("pid"))) {
            pid = params.get("pid");
            if (pid.equals(customerId)) {
                throw GlobalException.build("请勿扫自己的二维码");
            }
        }

        Map<String, String> salerParam = new HashMap<>();
        salerParam.put("customerId", customerId);
        salerParam.put("orgId", orgId);
        salerParam.put("orderType", "saler");
        Integer payMode = wxUser.getPayMode() + 2;
        salerParam.put("payType", payMode.toString());

        Map<String, String> ordParam = new HashMap<>();
        String orderSn = TransactionOrderUtil.TYPE_SHOP + TransactionOrderUtil.getPrimaryKey();
        ordParam.put("orderSn", orderSn);
        ordParam.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        ordParam.put("amount", "0");
        ordParam.put("pid", pid);
        ordParam.put("orgId", orgId);
        ordParam.put("customerId", customerId);
        ordParam.put("payStatus", "1");
        ordParam.put("orderType", "saler");
        ordParam.put("payType", payMode.toString());
        mallBoomService.addSalerOrder(ordParam);

//        HashMap<String, Object> salerOrderInfo = mallBoomService.getSalerOrder(salerParam);
//        if (null != salerOrderInfo) {//有订单
//            if ("0".equals(salerOrderInfo.get("payStatus").toString())) {
//                ordParam.put("orderSn", salerOrderInfo.get("orderSn").toString());
//                mallBoomService.editSalerOrder(ordParam);
//            } else {//订单已支付，直接返回
//                throw GlobalException.build("你已加入，请勿重复加入");
//            }
//        } else {
//            mallBoomService.addSalerOrder(ordParam);
//        }

        /**************************************开通联盟商家自动开通加盟代理***************************************/
        Integer salerPromoter = mallBoomService.getSalerPromoter(tmpParam);
        if (null != salerPromoter && 1 == salerPromoter) {
            Map<String, Object> promoterInfo = mallBoomService.getPromoterInfo(tmpParam);
            if (null != promoterInfo) {
                if (!"promoter".equals(promoterInfo.get("customerType")) && !"1".equals(promoterInfo.get("promoterStatus"))) {
                    if (!merchantSalerService.checkPromoter(orgId)) {
                        Map<String, String> proOrdParam = new HashMap<>();
                        String proOrderSn = TransactionOrderUtil.TYPE_SHOP + TransactionOrderUtil.getPrimaryKey();
                        proOrdParam.put("orderSn", proOrderSn);
                        proOrdParam.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                        proOrdParam.put("amount", "0");
                        proOrdParam.put("pid", "");
                        proOrdParam.put("orgId", orgId);
                        proOrdParam.put("customerId", customerId);
                        proOrdParam.put("payStatus", "1");
                        proOrdParam.put("orderType", "promoter");
                        proOrdParam.put("payType", payMode.toString());
                        mallBoomService.addSalerOrder(proOrdParam);
                        mallBoomService.savePromoter(customerId);
                        merchantSalerService.addPromoterNum(orgId);
                    }
                }
            }
        }
        /**************************************开通联盟商家自动开通加盟代理***************************************/

//        Map<String, String> agentParam = new HashMap<>();
//        agentParam.put("customerId", customerId);
//        agentParam.put("orgId", orgId);
//        agentParam.put("pCustomerId", pid);
//        Integer agentCount = mallBoomService.getAgentCount(agentParam);
//        if (agentCount == 0) {
//            merchantSalerService.addExtensionAgent(agentParam);//自动开通推广员
//        }
        this.addSaler(pid, customerId, orgId, 0);
        merchantSalerService.addSalerNum(orgId);
//        merchantSalerService.addPromoterNum(orgId);
//        merchantSalerService.addAgentNum(orgId);
        new Thread(() -> {
            try {
                Thread.sleep(1000L);
                this.getCasUser(customerId);
            } catch (Exception e) {
                LOGGER.error("获取小b的cas账号错误", e);
            }
        }).start();
        return true;
    }


    /**
     * 创建加盟代理
     *
     * @param params
     * @param request
     * @return
     * @throws GlobalException
     */
    @PostMapping("/createpromoterorder")
    public Object createPromoterOrder(@RequestBody Map<String, Object> params, HttpServletRequest request) throws GlobalException {
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        String openId = wxUser.getOpenid();

//        boolean checkPid = true;
//        String pid = "";

        String s = stringRedisTemplate.opsForValue().get("promoter_order_" + customerId + "_" + wxUser.getPayMode().toString());
        if (!StringUtils.isEmpty(s)) {
            throw GlobalException.build("操作过于频繁，请稍后再试");
        }

        if (StringUtils.isEmpty(params.get("pid"))) {
            params.put("pid", "");
        }
        String pid = merchantSalerService.customerCheck("promoter", customerId, orgId, params.get("pid").toString());
        if (!StringUtils.isEmpty(pid)) {
            String agentStatus = mallBoomService.getAgentCountStatus(pid);
            if ("1".equals(agentStatus)) {
                pid = "";
            }
        }


        //如果推广员被清退，则认为没有推广员
//        if(!StringUtils.isEmpty(params.get("pid"))){
//            String agentStatus = mallBoomService.getAgentCountStatus(params.get("pid").toString());
//            if("1".equals(agentStatus)){
//                checkPid = false;
//            }
//        }
//        if(checkPid){
//            pid = merchantSalerService.customerCheck("promoter", customerId, orgId, (String) params.get("pid"));
//        }
        if (pid.equals(customerId)) {
            throw GlobalException.build("请勿扫自己的二维码");
        }

        if (merchantSalerService.checkPromoter(orgId)) {
            throw GlobalException.build("达到上限,无法创建");
        }
        //B用户付钱，A用户受益
        String orderSn = TransactionOrderUtil.TYPE_SHOP + TransactionOrderUtil.getPrimaryKey();

//        HashMap<Object, Object> salerNowMap = new HashMap<>();
//        salerNowMap.put("orgId", orgId);
//        salerNowMap.put("customerId", customerId);
//        Integer salerNowCount = mallBoomService.getSalerCount(salerNowMap);
//        if (salerNowCount > 0) {
//            throw GlobalException.build("你已是联盟商家，无需开通");
//        }

        Integer sysAmount = mallBoomService.getJoinMoneyPromoter(orgId);
        if (null == sysAmount) {
            Map<String, Object> stringObjectMap = setInit(orgId);
            sysAmount = (Integer) stringObjectMap.get("seniorAmount");
        }
        if (null == params.get("amount")) {
            throw GlobalException.build("参数错误");
        }
        if (sysAmount != Integer.parseInt(params.get("amount").toString())) {
            throw GlobalException.build("金额不一致，请重试");
        }
//        String pid = "";
//        if (!StringUtils.isEmpty(params.get("pid"))) {
//            pid = params.get("pid").toString();
//            if (pid.equals(customerId)) {
//                throw GlobalException.build("请勿扫自己的二维码");
//            }
//        }

        Map<String, String> salerParam = new HashMap<>();
        salerParam.put("customerId", customerId);
        salerParam.put("orgId", orgId);
        salerParam.put("orderType", "promoter");
        Integer payMode = wxUser.getPayMode() + 2;
        salerParam.put("payType", payMode.toString());
        HashMap<String, Object> salerOrderInfo = mallBoomService.getSalerOrder(salerParam);

        if (null != salerOrderInfo) {//有订单
            if ("0".equals(salerOrderInfo.get("payStatus").toString())) {//订单未支付,取订单信息去支付
                Map<String, String> tmpParam = new HashMap<>();
                tmpParam.put("amount", sysAmount.toString());
                tmpParam.put("orderSn", orderSn);
                tmpParam.put("pid", pid);
                tmpParam.put("customerId", customerId);
                tmpParam.put("orgId", orgId);
                tmpParam.put("orderType", "promoter");
                tmpParam.put("payType", payMode.toString());
                tmpParam.put("orderSource", (String) params.get("orderSource"));
                mallBoomService.editSalerOrder(tmpParam);
            } else {//订单已支付，直接返回
                throw GlobalException.build("你已加入，请勿重复加入");
            }
        } else {//没有订单，创建订单去支付

            Map<String, String> tmpParam = new HashMap<>();
            tmpParam.put("orderSn", orderSn);
            tmpParam.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            tmpParam.put("amount", sysAmount.toString());
            tmpParam.put("pid", pid);
            tmpParam.put("orgId", orgId);
            tmpParam.put("customerId", customerId);
            tmpParam.put("payStatus", "0");
            tmpParam.put("orderType", "promoter");
            tmpParam.put("payType", payMode.toString());
            tmpParam.put("orderSource", (String) params.get("orderSource"));
            mallBoomService.addSalerOrder(tmpParam);
        }

        if (wxUser.getPayMode() == 2 || wxUser.getPayMode() == 3) {
            //app支付
            if ("2".equals(params.get("orderSource"))) {
                Map<String, Object> resParam = new HashMap<>();
                resParam.put("orderSn", orderSn);
                resParam.put("orderSource", params.get("orderSource"));
                return resParam;
            }

//            Map<String, Object> accountParam = new HashMap<>();
//            accountParam.put("customerId", customerId);
//            accountParam.put("orgId", orgId);
//            accountParam.put("openId", openId);
//            maiBaoLaService.checkCustomerAccount(accountParam);

            openId = wxUser.getPayOpenId();
            String agentFeeAccount = purchaseProcessService.getCustomerIdByFeeTypeAndOrdId(FeeConstants.AGENT_FEE, orgId, wxUser.getPayMode());//分账卡号
            Map<String, Object> reqMap = new HashMap<>();
            String frontUrl = "";
            if(!StringUtils.isEmpty(params.get("frontUrl"))){
                frontUrl = params.get("frontUrl").toString();
            }
            reqMap.put("frontUrl", frontUrl);//支付后跳转前端地址
            reqMap.put("cashAmount", sysAmount);//现金支付金额
            String cashSplitItems = this.getSplitItem(sysAmount, orderSn, orgId, "开通加盟代理", agentFeeAccount, wxUser.getPayMode());
            reqMap.put("cashSplitItems", cashSplitItems);//现金分账明细，JSON字符串
            reqMap.put("customerId", customerId);//支付用户ID
            reqMap.put("goodsName", "开通加盟代理");//商品描述
            reqMap.put("openID", openId);//支付用户OPENID
            reqMap.put("orderSn", orderSn);//平台订单ID
            reqMap.put("payeeAccountNumber", agentFeeAccount);//收款用户帐号(收款用户为机构会员时必填，机构结算标识)
            reqMap.put("payeeUserID", purchaseProcessDao.getAccountUidByOrgId(orgId));//收款用户ID

            // 行业代码
            String industryCode = purchaseProcessDao.getOrgMerchantInfoByOrgId(orgId);
            reqMap.put("industryCode", industryCode);
            // 行业名称
            String industryName = purchaseProcessDao.getIndustryNameByCode(industryCode);
            reqMap.put("industryName", industryName);
            // 应用appId
            String appId = "";
            if (wxUser.getPayMode() == 3) {
                appId = purchaseProcessDao.getAppIdByOrgId("linker");
            }
            if (wxUser.getPayMode() == 2) {
                appId = purchaseProcessDao.getAppIdByOrgId(orgId);
            }
            reqMap.put("appId", appId);
            String alias = "";
            if (wxUser.getPayMode() == 3) {
                alias = maiBaoLaService.getAliasByLinker();
            }
            if (wxUser.getPayMode() == 2) {
                alias = maiBaoLaService.getAlias(orgId);
            }
            reqMap.put("clintType", alias);
            // 支付方式：WX-公众号支付；XCX-微信小程序支付
            reqMap.put("payType", "WX");
            // 访问终端类型:1手机；2PC
            reqMap.put("source", 1);
            // 交易验证方式：0-无验证；1-短信验证码；2-支付密码
            reqMap.put("validateType", 0);

            String result = "";
            String url = wcPayProperties.getAcsurl() + WcPayConstant.TRADE_PAY_ORDER;
            try {
                // 积分抵扣为0元
                result = httpService.doPost(url, com.alibaba.fastjson.JSON.toJSONString(reqMap), WcPayConstant.JSON);
                result = purchaseProcessService.callResultProcess(result);
            } catch (Exception e) {
                LOGGER.error("支付网关调用异常", e);
                throw GlobalException.build("支付网关调用异常");
            }
            Map res = (Map) JSON.parse(result);
            // noinspection unchecked
            res.put("orderSn", orderSn);
            res.put("orderSource", params.get("orderSource"));
            stringRedisTemplate.opsForValue().set("promoter_order_" + customerId + "_" + wxUser.getPayMode().toString(), "1", 200, TimeUnit.SECONDS);
            return res;
        } else {
            SortedMap<String, Object> finalpackage = new TreeMap<>();
            Map<String, String> orderParam = new HashMap<>();
            Long currentTime = new Date().getTime();
            String notifyUrl = systemProperties.getScrmUrl() + "/acs/merchantsaler/ordernotify";
            orderParam.put("body", "开通加盟代理");
            orderParam.put("notifyUrl", notifyUrl);
            orderParam.put("openid", openId);
            orderParam.put("outTradeNo", orderSn);
            orderParam.put("timestamp", currentTime.toString());
            orderParam.put("totalFee", sysAmount.toString());
            orderParam.put("tradeType", "JSAPI");
            orderParam.put("wcpayType", "STEPLINK_" + orgId);
            // todo
            if (systemProperties.isWxSplit()) {
                orderParam.put("needShare", "1");
            }
            Map<String, String> appSign = ParamSignUtils.sign(orderParam);
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("appSign", appSign.get("appSign")));
            nvps.add(new BasicNameValuePair("notifyUrl", orderParam.get("notifyUrl")));
            nvps.add(new BasicNameValuePair("body", orderParam.get("body")));
            nvps.add(new BasicNameValuePair("outTradeNo", orderParam.get("outTradeNo")));
            nvps.add(new BasicNameValuePair("openid", orderParam.get("openid")));
            nvps.add(new BasicNameValuePair("timestamp", orderParam.get("timestamp")));
            nvps.add(new BasicNameValuePair("totalFee", orderParam.get("totalFee")));
            nvps.add(new BasicNameValuePair("tradeType", orderParam.get("tradeType")));
            nvps.add(new BasicNameValuePair("wcpayType", orderParam.get("wcpayType")));
            if (systemProperties.isWxSplit()) {
                nvps.add(new BasicNameValuePair("needShare", orderParam.get("needShare")));
            }
            String result = ParamSignUtils.callService(payurl + "/pay/wcpay", nvps, 0, 0);
            LOGGER.info("result===[{}]", result);
            Object parse = JSON.parse(result);
            Map ret = (Map) parse;
            if ((Integer) ret.get("rt") != 1) {
                throw GlobalException.build("微信签名失败");
            } else {
                Map retInfo = (Map) ret.get("object");
                finalpackage.put("appId", retInfo.get("appId"));
                finalpackage.put("timeStamp", retInfo.get("timeStamp"));
                finalpackage.put("nonceStr", retInfo.get("nonceStr"));
                finalpackage.put("package", "prepay_id=" + retInfo.get("prepayId"));
                finalpackage.put("signType", retInfo.get("signType"));
                finalpackage.put("paySign", retInfo.get("paySign"));
                finalpackage.put("orderSn", orderSn);
                finalpackage.put("orderSource", params.get("orderSource"));
            }
            stringRedisTemplate.opsForValue().set("promoter_order_" + customerId + "_" + wxUser.getPayMode().toString(), "1", 200, TimeUnit.SECONDS);
            return finalpackage;
        }
    }


    /**
     * 直接加入加盟代理（金额等于0）
     *
     * @param params
     * @param request
     * @return
     */
    @PostMapping("/joinpromoterdirect")
    public Object joinPromoterDirect(@RequestBody Map<String, String> params, HttpServletRequest request) throws GlobalException {
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();

        String pid = merchantSalerService.customerCheck("promoter", customerId, orgId, params.get("pid"));
        if (!StringUtils.isEmpty(pid)) {
            String agentStatus = mallBoomService.getAgentCountStatus(pid);
            if ("1".equals(agentStatus)) {
                pid = "";
            }
        }

//        boolean checkPid = true;
//        String pid = "";
//        //如果推广员被清退，则认为没有推广员
//        if(!StringUtils.isEmpty(params.get("pid"))){
//            String agentStatus = mallBoomService.getAgentCountStatus(params.get("pid"));
//            if("1".equals(agentStatus)){
//                checkPid = false;
//            }
//        }
//        if(checkPid){
//            pid = merchantSalerService.customerCheck("promoter", customerId, orgId, params.get("pid"));
//        }
        if (pid.equals(customerId)) {
            throw GlobalException.build("请勿扫自己的二维码");
        }

//        if (2 == wxUser.getPayMode()) {
//            Map<String, Object> accountParam = new HashMap<>();
//            accountParam.put("customerId", customerId);
//            accountParam.put("orgId", orgId);
//            accountParam.put("openId", openId);
//            maiBaoLaService.checkCustomerAccount(accountParam);
//        }

        if (merchantSalerService.checkPromoter(orgId)) {
            throw GlobalException.build("达到上限,无法创建");
        }
        Map<String, String> tmpParam = new HashMap<>();
        tmpParam.put("orgId", orgId);
        tmpParam.put("customerId", customerId);
        Integer salerCount = mallBoomService.getPromoterCount(tmpParam);
        if (salerCount > 0) {
            throw GlobalException.build("你已加入加盟代理，请勿重复加入");
        }
        String isSaler = "";
        if (!StringUtils.isEmpty(pid)) {
            //判断分享人是否是麦或高级推广员
            HashMap<Object, Object> salerMap = new HashMap<>();
            salerMap.put("orgId", orgId);
            salerMap.put("customerId", pid);
            Integer checkSalerCount = mallBoomService.getSalerCount(salerMap);
            if (checkSalerCount > 0) {
                isSaler = "1";
            }
        }

        Integer amount = mallBoomService.getJoinMoneyPromoter(orgId);
        if (null == amount) {
            Map<String, Object> stringObjectMap = setInit(orgId);
            amount = (Integer) stringObjectMap.get("seniorAmount");
        }
        if (amount > 0 && "".equals(isSaler)) {
            throw GlobalException.build("非法操作");
        }

        Map<String, String> salerParam = new HashMap<>();
        salerParam.put("customerId", customerId);
        salerParam.put("orgId", orgId);
        salerParam.put("orderType", "promoter");
        Integer payMode = wxUser.getPayMode() + 2;
        salerParam.put("payType", payMode.toString());

        Map<String, String> ordParam = new HashMap<>();
        String orderSn = TransactionOrderUtil.TYPE_SHOP + TransactionOrderUtil.getPrimaryKey();
        ordParam.put("orderSn", orderSn);
        ordParam.put("createTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        ordParam.put("amount", "0");
        ordParam.put("pid", pid);
        ordParam.put("orgId", orgId);
        ordParam.put("customerId", customerId);
        ordParam.put("payStatus", "1");
        ordParam.put("orderType", "promoter");
        ordParam.put("payType", payMode.toString());

        HashMap<String, Object> salerOrderInfo = mallBoomService.getSalerOrder(salerParam);
        if (null != salerOrderInfo) {//有订单
            if ("0".equals(salerOrderInfo.get("payStatus").toString())) {
                ordParam.put("orderSn", salerOrderInfo.get("orderSn").toString());
                mallBoomService.editSalerOrder(ordParam);
            } else {//订单已支付，直接返回
                throw GlobalException.build("你已加入加盟代理，请勿重复加入");
            }
        } else {
            mallBoomService.addSalerOrder(ordParam);
        }
        if (!StringUtils.isEmpty(pid)) {
            this.savePCustomer(customerId, pid, orgId);
        }
        merchantSalerService.addPromoterNum(orgId);
        return mallBoomService.savePromoter(customerId);
    }


    /**
     * 开通推广员
     */
    @PostMapping("/joinextensionagent")
    public Boolean joinExtensionAgent(HttpServletRequest request, @RequestBody Map<String, String> params) throws GlobalException {
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();

        String pCustomerId = merchantSalerService.customerCheck("agent", customerId, orgId, params.get("pid"));
        Map<String, String> salerInfo = merchantSalerService.getSalerInfo(pCustomerId, orgId);
        if (null == salerInfo || StringUtils.isEmpty(salerInfo.get("customerId"))) {
            pCustomerId = "";
        }
        if (pCustomerId.equals(customerId)) {
            throw GlobalException.build("请勿扫自己的二维码");
        }

        if (merchantSalerService.checkAgent(orgId)) {
            throw GlobalException.build("推广员数量已达上线");
        }

        Map<String, String> tmpParam = new HashMap<>();
        tmpParam.put("customerId", customerId);
        tmpParam.put("orgId", orgId);
        tmpParam.put("pCustomerId", pCustomerId);
        Integer agentCount = mallBoomService.getAgentCount(tmpParam);
        if (agentCount > 0) {
            throw GlobalException.build("你已是推广员,无需重复加入");
        }
        //推广员同时也是加盟代理 把用户设置成加盟代理
        //mallBoomService.savePromoter(customerId);

        //查询该用户名称
        String customerName = mallBoomService.findCustomerName(customerId);
        //组合推广员账单信息
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", customerId);
        map.put("customerName", customerName);
        //该用户信息添加到推广员账单信息表中
        mallBoomService.openAccount(map);
        if (!"".equals(pCustomerId)) {
            this.savePCustomer(customerId, pCustomerId, orgId);
        }
        merchantSalerService.addAgentNum(orgId);
        return merchantSalerService.addExtensionAgent(tmpParam);
    }


    /**
     * 联盟商家首页信息
     *
     * @param request
     * @return
     */
    @GetMapping("/getmerchantinfo")
    public Map getMerchantInfo(HttpServletRequest request) {
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();

        String businessName = wxUser.getNickname() + "的小店";
        Map<String, String> salerInfo = merchantSalerService.getStoreInfo(customerId, orgId, 2);
        if (null != salerInfo && !StringUtils.isEmpty(salerInfo.get("businessName"))) {
            businessName = salerInfo.get("businessName");
        }

//        Map<String, String> orgInfo = merchantSalerService.getOrgInfo(orgId);
//        if(null != orgInfo && !StringUtils.isEmpty(orgInfo.get("salerName"))){
//            businessName = orgInfo.get("salerName");
//        }

        //累计收益 元
        Integer sumIncome = merchantSalerService.getSumGoodsMoney(customerId, orgId);
        String profit = NumberUtils.fenToYuan(Long.valueOf(sumIncome));
        if ("".equals(profit)) {
            profit = "0.00";
        }

        //待结算 元
//        Long zCustomerFreeze = merchantSalerService.getProfitToSettlement(customerId, orgId);
        Map<String, Object> params = new HashMap<>();
        params.put("tradeType", -1);
        params.put("customerId", customerId);
        params.put("customerType", 1);
        Long zCustomerFreeze = merchantSalerService.getCustomerFreeze(params);

        String profitToSettlement = NumberUtils.fenToYuan(zCustomerFreeze);
        if ("".equals(profitToSettlement)) {
            profitToSettlement = "0.00";
        }

        //累计订单
        Integer merchantOrderCount = merchantSalerService.getMerchantOrderCount(customerId);

        //可提现金额 元
        Integer zCustomerBalance = merchantSalerService.getProfitWithdrawable(customerId, orgId);
        String profitWithdrawable = "0.00";
        if (!StringUtils.isEmpty(zCustomerBalance)) {
            profitWithdrawable = NumberUtils.fenToYuan(Long.valueOf(zCustomerBalance));
        }

        //今日收益 元
        Integer sumIncomeToday = merchantSalerService.getSumGoodsMoneyToday(customerId, orgId);
        String profitToday = "0.00";
        if (!StringUtils.isEmpty(sumIncomeToday)) {
            profitToday = NumberUtils.fenToYuan(Long.valueOf(sumIncomeToday));
        }

        //今日订单
        Integer merchantOrderCountToday = merchantSalerService.getMerchantOrderCountToday(customerId);

        //商品订单 待发货
        Integer MerchantOrderCountToSend = merchantSalerService.getMerchantOrderCountToSend(customerId);

        //推广员个数
        Integer agentCount = merchantSalerService.getAgentCount(customerId, orgId);

        Map<String, Object> data = new HashMap<>();
        data.put("businessName", businessName);
        data.put("belongName", wxUser.getNickname() + "所有");
        data.put("agentCount", agentCount);
        data.put("merchantOrderCount", merchantOrderCount);
        data.put("merchantOrderCountToday", merchantOrderCountToday);
        data.put("MerchantOrderCountToSend", MerchantOrderCountToSend);

        data.put("profit", profit);
        data.put("profitToSettlement", profitToSettlement);
        data.put("profitWithdrawable", profitWithdrawable);
        data.put("profitToday", profitToday);
        return data;
    }


    /**
     * 获取我的推广员列表
     *
     * @param request
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @GetMapping("/getextensionagentlist")
    public PageInfo getExtensionAgentList(HttpServletRequest request,
                                          @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                          @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize) {
        PageHelper.startPage(pageIndex, pageSize);
        WxUser wxUser = requestFilter.getWxUser(request);
        String customerId = wxUser.getCustomerId();
        String orgId = wxUser.getOrgId();
        Integer payMode = wxUser.getPayMode();

        List<Map<String, String>> extensionAgentList = merchantSalerService.getExtensionAgentList(customerId, orgId);
        for (Map<String, String> val : extensionAgentList) {
            val.put("noName", "0");
            //  如果用户名称为空则显示用户名称为手机号4位
            if (StringUtils.isEmpty(val.get("customerName"))) {
                val.put("noName", "1");
                if (!StringUtils.isEmpty(val.get("phone"))) {
                    String customerPhone = val.get("phone");
                    val.put("customerName", "手机尾号" + customerPhone.substring(customerPhone.length() - 4) + "用户");
                }
            }
            Integer sonCount = merchantSalerService.getSonCustomerCount(val.get("customerId"), orgId, payMode + 2);
            val.put("SonCustomerCount", sonCount.toString());
            val.remove("phone");
        }
        return new PageInfo<>(extensionAgentList);
    }


    /**
     * 推广员列表-查看
     *
     * @param request
     * @param pageIndex
     * @param pageSize
     * @param customerId
     * @return
     */
    @GetMapping("/getcustomersonlist")
    public PageInfo getCustomerSonList(HttpServletRequest request,
                                       @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                       @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                       @RequestParam(value = "customerId", defaultValue = "", required = true) String customerId
    ) throws GlobalException {
        if (StringUtils.isEmpty(customerId)) {
            throw GlobalException.build("参数错误");
        }
        PageHelper.startPage(pageIndex, pageSize);
        WxUser wxUser = requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        Integer payMode = wxUser.getPayMode();

        List<Map<String, String>> CustomerSonList = merchantSalerService.getCustomerSonListAgent(customerId, orgId, payMode + 2);

        return new PageInfo<>(CustomerSonList);
    }


    /**
     * 推广员首页信息
     *
     * @param request
     * @return
     */
    @GetMapping("/getpromoterinfo")
    public Map getPromoterInfo(HttpServletRequest request) {
        WxUser wxUser = requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        String customerId = wxUser.getCustomerId();
        String nickname = wxUser.getNickname();
        Map<String, String> customerBaseInfo = merchantSalerService.getCustomerBaseInfo(customerId);

        Map<String, String> orgInfo = merchantSalerService.getOrgInfo(orgId);
        String promoterName = "推广员";
        if (null != orgInfo && !StringUtils.isEmpty(orgInfo.get("promoterName"))) {
            promoterName = orgInfo.get("promoterName");
        }

        Integer payMode = wxUser.getPayMode();
//        Map<String, String> salerInfo = merchantSalerService.getSalerInfo(customerId, orgId);
//        String promoterName = merchantSalerService.getPromoterName(customerId,orgId);
//        if(StringUtils.isEmpty(promoterName)){
//            promoterName = "推广员";
//        }
        Integer sonCustomerCount = merchantSalerService.getSonCustomerCount(customerId, orgId, payMode + 2);

        Map<String, Object> data = new HashMap<>();
        data.put("customerId", customerId);
        data.put("promoterName", promoterName);
        data.put("customerName", nickname);
        data.put("customerAvatar", customerBaseInfo.get("customerAvatar"));
        data.put("sonCustomerCount", sonCustomerCount);
        data.put("agentStatus", mallBoomService.getAgentCountStatus(customerId));
        return data;
    }


    /**
     * 保存用户关系
     *
     * @param pid
     * @param customerId
     * @param orgId
     * @param payMoney
     * @return
     */
    public Boolean addSaler(String pid, String customerId, String orgId, Integer payMoney) {
        Map<String, Object> salerParam = new HashMap<>();
        salerParam.put("customerId", customerId);
        salerParam.put("pid", pid);
        salerParam.put("joinTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        salerParam.put("payMoney", payMoney);
        salerParam.put("orgId", orgId);
        salerParam.put("phone", "");
        int count = mallBoomService.getSalerCount(salerParam);
        if (count > 0) {
            return true;
        } else {
            return mallBoomService.addSaler(salerParam);
        }
    }

    @RequestMapping("/getimage")
    public Map<String, Object> getImage(HttpServletRequest request) {
        WxUser wxUser = requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        Map<String, Object> result = merchantSettingService.getImage(orgId);
        if (result == null || StringUtils.isEmpty(result.get("salerImg")) || StringUtils.isEmpty(result.get("agentImg"))) {
            String salerImg = merchantSettingService.getModeImage(1);
            String agentImg = merchantSettingService.getModeImage(2);
            if (result != null) {
                if (!StringUtils.isEmpty(result.get("salerImg"))) {
                    salerImg = result.get("salerImg").toString();
                }
                if (!StringUtils.isEmpty(result.get("agentImg"))) {
                    agentImg = result.get("agentImg").toString();
                }
            }
            Map<String, Object> temp = new HashMap<>();
            temp.put("salerImg", salerImg);
            temp.put("agentImg", agentImg);
            return temp;
        }
        return result;
    }


    /**
     * 计算各类抽成
     */
    private String getSplitItem(Integer sysAmount, String orderSn, String orgId, String note, String merchantFeeAccount, Integer payMode) throws GlobalException {
        Map<String, String> cutPercent = mallBoomService.getOrgCutByOrgId(orgId);

        List<Map<String, Object>> cashSplitItems = new ArrayList<>();
        String linkdrawfeeaccount = purchaseProcessService.getCustomerIdByFeeTypeAndOrdId(FeeConstants.LINK_DRAW_FEE, orgId, payMode);
        Integer linkerCut = this.getCutMoney(sysAmount, cutPercent.get("linkerTake"));
        Map<String, Object> cashSplitItem1 = new HashMap<>();
        cashSplitItem1.put("customerId", linkdrawfeeaccount);
//        cashSplitItem1.put("customerAccountNumber", linkdrawfeeaccount);
        cashSplitItem1.put("splitAmount", linkerCut);
        cashSplitItem1.put("note", note + "联汇支付抽成");
        cashSplitItem1.put("orderId", orderSn);
        cashSplitItems.add(cashSplitItem1);

        String orgdrawfeeaccount = purchaseProcessService.getCustomerIdByFeeTypeAndOrdId(FeeConstants.ORG_DRAW_FEE, orgId, payMode);
        Integer unionbarleyCut = this.getCutMoney(sysAmount, cutPercent.get("unionbarleyTake"));
        Map<String, Object> cashSplitItem2 = new HashMap<>();
        cashSplitItem2.put("customerId", orgdrawfeeaccount);
//        cashSplitItem2.put("customerAccountNumber", orgdrawfeeaccount);
        cashSplitItem2.put("splitAmount", unionbarleyCut);
        cashSplitItem2.put("note", note + "联盟大麦支付抽成");
        cashSplitItem2.put("orderId", orderSn);
        cashSplitItems.add(cashSplitItem2);

        Map<String, Object> cashSplitItem3 = new HashMap<>();
        cashSplitItem3.put("customerId", merchantFeeAccount);
//        cashSplitItem3.put("customerAccountNumber", merchantFeeAccount);
        cashSplitItem3.put("splitAmount", sysAmount - linkerCut - unionbarleyCut);
        cashSplitItem3.put("note", note + "剩余费用");
        cashSplitItem3.put("orderId", orderSn);
        cashSplitItems.add(cashSplitItem3);

        return JSON.serialize(cashSplitItems);
    }


    /**
     * 计算抽成金额
     *
     * @param sysAmount  订单金额
     * @param cutPercent 抽成比例
     * @return
     */
    private Integer getCutMoney(Integer sysAmount, String cutPercent) {
        double v = sysAmount.doubleValue() * Double.valueOf(cutPercent) / 100;
        return new BigDecimal(v).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
    }

    @GetMapping("/getallpagelist")
    public Map<String, Object> getAllPageList(@RequestParam(value = "customerId", defaultValue = "", required = false) String customerId,
                                              @RequestParam(value = "isAllIntegral", defaultValue = "", required = false) Integer isAllIntegral,
                                              HttpServletRequest request) {
        WxUser wxUser = requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        if (StringUtils.isEmpty(customerId)) {
            customerId = orgId;
        }
        // 获取对应的页面ID
        Integer id = merchantSalerService.getHomePageIdByCustomerId(customerId);
        if (StringUtils.isEmpty(id)) {
            throw GlobalException.build(404, "页面不存在");
        }
        if(StringUtils.isEmpty(isAllIntegral)){
            isAllIntegral = 0;
        }
        //        List<Map<String, Object>> result = merchantSalerService.getPageList(orgId, customerId);
        //  缓存ing
        return merchantSalerService.getPageInfo(id, 0, false,request,true, isAllIntegral);
    }

    @GetMapping("/getpageallenrolllist")
    public PageInfo getPageAllEnrollList(String id,
                                         @RequestParam(value = "keyword", defaultValue = "", required = false) String keyword,
                                         @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                         @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                         HttpServletRequest request) {
        WxUser wxUser = requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        PageHelper.startPage(pageIndex, pageSize);
        Map<String, Object> param = new HashMap<>();
        param.put("keyword", keyword);
        param.put("id", id);
        param.put("orgId", orgId);
        return new PageInfo<>(merchantSalerService.getPageAllEnrollList(param));
    }

    @GetMapping("/getPageAllFormlist")
    public Object getPageAllFormlist(String id,
                                         @RequestParam(value = "keyword", defaultValue = "", required = false) String keyword,
                                         @RequestParam(value = "pageIndex", defaultValue = "1", required = false) int pageIndex,
                                         @RequestParam(value = "pageSize", defaultValue = "10", required = false) int pageSize,
                                         HttpServletRequest request) {
        WxUser wxUser = requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        Map<String, Object> param = new HashMap<>();
        param.put("formTitle", keyword);
        param.put("id", id);
        param.put("orgId", orgId);
        param.put("pageIndex", pageIndex);
        param.put("pageSize", pageSize);
        return merchantSalerService.getPageAllFormlist(param,request);
    }


    /**
     * 获取加盟代理、推广员审核状态
     *
     * @param request
     * @return
     */
    @GetMapping("/getcustomercheckstatus")
    public Map<String, Object> getCustomerCheck(HttpServletRequest request, @RequestParam(value = "type", defaultValue = "", required = true) String type) {
        if (StringUtils.isEmpty(type)) {
            throw GlobalException.build("参数错误");
        }
        WxUser wxUser = requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        String customerId = wxUser.getCustomerId();
        Map<String, String> param = new HashMap<>(3);
        param.put("orgId", orgId);
        param.put("customerId", customerId);
        param.put("type", type);
        return merchantSalerService.getCustomerCheckInfo(param);
    }


    @GetMapping("/getcustomposterlist")
    public List<Map<String, Object>> getcustomposer(HttpServletRequest request,
                                                    @RequestParam(value = "posterKey") String posterKey,
                                                    @RequestParam(value = "posterType") String posterType) {
        if (StringUtils.isEmpty(posterKey) || StringUtils.isEmpty(posterType)) {
            throw GlobalException.build("参数错误");
        }
        WxUser wxUser = requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        Map<String, Object> params = new HashMap<>();
        params.put("orgId", orgId);
        params.put("posterKey", posterKey);
        params.put("posterType", posterType);
        return merchantSalerService.getCustomPosterList(params);
    }


    protected Map<String, Object> setInit(String orgId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orgId", orgId);
        params.put("freezeTime", 30);
        params.put("amount", 0);
        params.put("rebate", 0);
        params.put("recommend", 0);
        params.put("seniorAmount", 0);
        params.put("seniorRebate", 0);
        params.put("serviceRatio", 50);
        params.put("recommendRatio", 50);
        params.put("platformRatio", 0);
        params.put("unhappen", 1);
        params.put("agentCheck", 0);
        params.put("promoterCheck", 0);
        params.put("salerPromoter", 0);
        mallBoomService.setInit(params);
        return params;
    }


    /**
     * 获取导航
     *
     * @param customerId
     * @param request
     * @return
     */
    @GetMapping("/getfooterlist")
    public Map<String, Object> getFooterList(
            @RequestParam(value = "customerId", defaultValue = "", required = false) String customerId,
            HttpServletRequest request
    ) {
        WxUser wxUser = requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        if (StringUtils.isEmpty(customerId)) {
            customerId = orgId;
        }
        Map<String, Object> result;

        String key = "footerList:" + customerId;
        String footerListStr = stringRedisTemplate.opsForValue().get(key);
        //  缓存ing
        if (StringUtils.isEmpty(footerListStr)) {
            // 分布式锁
            String temp = UUID.randomUUID().toString();
            Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(key + ":lock", temp, 10, TimeUnit.SECONDS);
            if (lock != null && lock) {
                result = merchantSalerService.getFooterList(customerId);
                stringRedisTemplate.opsForValue().set(key, com.alibaba.fastjson.JSON.toJSONString(result, SerializerFeature.WriteMapNullValue), 1, TimeUnit.DAYS);
                if (temp.equals(stringRedisTemplate.opsForValue().get(key + ":lock"))) {
                    stringRedisTemplate.delete(key + ":lock");
                }
            } else {
                throw GlobalException.build("网络开小差了");
            }
        } else {
            result = (Map<String, Object>) com.alibaba.fastjson.JSON.parse(footerListStr);
        }
        return result;
    }


    /**
     * 获取 页面id对应的页面数据
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/pageinfo")
    public Map<String, Object> pageInfo(
            @RequestParam(value = "id") Integer id,
            HttpServletRequest request
    ) {
        if (StringUtils.isEmpty(id)) {
            throw GlobalException.build("参数错误！");
        }
        //  缓存ing
        return merchantSalerService.getPageInfo(id, 0, false,request,true,null);
    }

    /**
     * 获取 个人中心营销活动
     *
     * @param request
     * @return
     */
    @GetMapping("/getUserCenter")
    public Map pageInfo(
            HttpServletRequest request
    ) {
        WxUser wxUser = requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        String key = "userCenter:" + orgId;
        Map map;
        String userCenterString = stringRedisTemplate.opsForValue().get(key);
        if(StringUtils.isEmpty(userCenterString)){
            map = merchantSalerService.getUserCenter(orgId);
            if(map==null){
                map = new HashMap();
                map.put("pageColour",null);
                map.put("pageName","个人中心");
                map.put("pageTitle","个人中心");
                map.put("pageInfo","推荐你看看，精选好货等你选!");
            }
        }else {
            map = (Map) com.alibaba.fastjson.JSON.parse(userCenterString);
        }
        List<Map<String, Object>> markings = merchantSalerService.getMarkings(orgId);
        map.put("markings",markings);
        return map;
    }

    /**
     * 获取 浮窗数据
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/windowInfo")
    public Map<String, Object> windowInfo(
            HttpServletRequest request
    ) {
        WxUser wxUser = requestFilter.getWxUser(request);
        String orgId = wxUser.getOrgId();
        //  缓存ing
        return merchantSalerService.windowInfo(orgId);
    }
}
